//
//  KCNoVisitorController.swift
//  MyKC
//
//  Created by yy on 2017/3/27.
//  Copyright © 2017年 com.yasuo. All rights reserved.
//

import UIKit
import MapKit
import CoreLocation
import YYModel
import SVProgressHUD
//import BaiduMapAPI

class KCNoVisitorController: UIViewController {
    var planModel:KCPlanModel = KCPlanModel()
//    var storeId: String = ""
//    var taskPlanId:String = ""
    
    lazy var timeView = KCPlanTimeView.planTimeView()
    lazy var timer = Timer()
    //地图管理器
    lazy var mgr = CLLocationManager()
    
    //定位经纬度
    var location:String?
    //定位地址信息
    var localAddress:String?
    
    //添加地图
    lazy var mapView: MKMapView = {
        let mapView = MKMapView()
        mapView.mapType = .standard
        mapView.showsScale = true
        mapView.showsCompass = true
        mapView.showsTraffic = true
        mapView.showsUserLocation = true
        mapView.userTrackingMode = .follow
        return mapView
    }()
    
    lazy var btnSign: UIButton = {
        let signBtn = UIButton(fontSize: 15, title: "签到并拜访")
        signBtn.layer.cornerRadius = 5
        signBtn.clipsToBounds = true
        signBtn.backgroundColor = colorRGB(r: 26, g: 147, b: 246)
        signBtn.frame = CGRect(x: 60, y: ScreenHeight - 60, width: ScreenWidth - 120, height: 40)
        return signBtn
    }()

    @IBOutlet weak var timeContainView: UIView!
    
    @IBOutlet weak var mapContainView: UIView!
    
    @IBOutlet weak var lbe_storeName: UILabel!
    @IBOutlet weak var lbe_storeNo: UILabel!
    
    @IBOutlet weak var lbe_storeAddress: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        getData()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBar.subviews[0].alpha = 0
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        if #available(iOS 9.0, *) {
            mapView.delegate = nil
        } else {
            // Fallback on earlier versions
        }
        mgr.delegate = nil
//        mgr = nil
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
    }
    
    deinit {
        timer.invalidate()
        print("色了")
    }
}

// MARK: -  设置界面基本信息
extension KCNoVisitorController {
    internal func setupUI() {
        //添加设置上面的timeView
        timeView.frame = timeContainView.frame
        timeContainView.addSubview(timeView)
        timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(repeatTime), userInfo: nil, repeats: true)
        RunLoop.current.add(timer, forMode: .commonModes)
        
        //设置添加下面的
        mapView.frame = mapContainView.bounds
        mapView.delegate = self
        mapContainView.addSubview(mapView)

        
        mgr.delegate = self
        //请求授权的方法-------
        mgr.requestWhenInUseAuthorization()
        mgr.startUpdatingLocation()
        
        //添加上面的签到按钮
        view.addSubview(btnSign)
        btnSign.addTarget(self, action: #selector(signBtnClick(sender:)), for: .touchUpInside)
    }
    
    // MARK: -  下面的签到按钮点击事件
    @objc private func signBtnClick(sender: UIButton) {
        //签到按钮点击事件
        if isLocalEnable() == false {
            return
        }
        //上传网络数据
        SVProgressHUD.show()
        let paraDic = ["TaskPlanId":planModel.TaskPlanId,"Address":localAddress,"Location":location]
        KCNetworkManager.sharedTools.request(method: .POST, urlString: "/api/TaskPlan/CheckInForApp", parameters: paraDic) { [weak self] (response, error) in
            SVProgressHUD.dismiss()
            guard response != nil else {
                //说明没有返回数据
                return
            }
            //跳转到工作页面----------
            let montnController = KCMontnReportController()
            montnController.model = (self?.planModel)!
            self?.navigationController?.pushViewController(montnController, animated: true)
        }
    }
    
    func isLocalEnable() -> Bool {
        var isEnable = false
        if CLLocationManager.locationServicesEnabled() == true || CLLocationManager.authorizationStatus() == .authorizedAlways || CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
            if location?.characters.count == 0 || localAddress?.characters.count == 0 {
                //定位失败了 说明
                SVProgressHUD.showError(withStatus: "定位失败")
            }else {
                isEnable = true
            }
        }
        //说明定位没有打开
        else {
            SVProgressHUD.showError(withStatus: "请打开定位设置")
        }
        return isEnable
    }
    
    @objc private func repeatTime() {
        sharedDateFormater.dateFormat = "hh:mm:ss"
        //设置为当前时区
        sharedDateFormater.locale = Locale.current
        timeView.lbe_currentTime.text = sharedDateFormater.string(from: Date.init())
        sharedDateFormater.dateFormat = "yyyy年MM月dd日"
        let dateString = sharedDateFormater.string(from: Date.init())
        sharedDateFormater.dateFormat = "EEEE"
        let stringWeekKey = sharedDateFormater.string(from: Date.init())
        let dic = ["Monday":"星期一","Tuesday":"星期二","Wednesday":"星期三","Thursday":"星期四","Friday":"星期五","Saturday":"星期六","Sunday":"星期日"]
        guard let weekString = dic[stringWeekKey] else {
            return
        }
        timeView.lbe_currentDate.text = dateString + "" + weekString
    }
}

// MARK: -  地图的定位和-----------
extension KCNoVisitorController:MKMapViewDelegate,CLLocationManagerDelegate {
    // MARK: -  这个是定位开始改变时候调用的方法--------------
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else {
            return
        }
        //停止获取定位信息-------
        mgr.stopUpdatingLocation()
        var region = MKCoordinateRegion()
        region.center = location.coordinate
        if #available(iOS 9.0, *) {
            mapView.setRegion(region, animated: true)
        } else {
            // Fallback on earlier versions
        }
    }
    
    func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
        let geocoder = CLGeocoder()
        guard let location = userLocation.location else { return }
        geocoder.reverseGeocodeLocation(location) { (placeMarks, error) in
            if placeMarks?.count == 0 || error != nil {
                return
            }
            let placeMark = placeMarks?.last
            userLocation.title = placeMark?.locality
            userLocation.subtitle = placeMark?.name
        }
    }
}

// MARK: -  获取当前的数据---------
extension KCNoVisitorController {
    internal func getData() {
        KCNetworkManager.sharedTools.request(method: .GET, urlString: "/api/Task/GetStoreDetail", parameters: ["StoreId":planModel.StoreId]) { [weak self] (response, error) in
            guard let response = response as? NSDictionary,let responseContent = response["Content"] as? NSDictionary else {
                return
            }
            let model = KCAddressViewModel()
            model.yy_modelSet(with: responseContent as! [AnyHashable : Any])
//            model = NSDictionary.yy_modelSet(withJSON: <#T##Any#>)
            self?.lbe_storeName.text = model.StoreName
            self?.lbe_storeNo.text = model.StoreNo
            self?.lbe_storeAddress.text = model.Address
        }
    }
}



